/**
 * 带有Form的Modal弹窗组件
 * on 2020.02.25
 * add by lifenping
 */

import { Modal, Form } from 'antd';
import React, { Component } from 'react';
// import { FormComponentProps } from '@ant-design/compatible/es/form';

export interface propsType {
  onCancel: () => void;
  okHandle: (values: any) => void;
  afterClose: () => void;
  submitText?: string;
  cancelText?: string;
  visible: boolean;
  children: any;
  colon?: boolean;
  // Form中的属性
  layout?: any;
  itemLayout?: {};
  form: any;
  title?: any;
}

class ModalForm extends Component<propsType> {
  static defaultProps = {
    visible: false,
    colon: true,
    layout: 'horizontal',
    itemLayout: {
      labelCol: { span: 6 },
      wrapperCol: { span: 12 },
    },
  };

  okHandle = () => {
    const { okHandle, form } = this.props;
    form.validateFields((errs: any, fields: any) => {
      if (!errs && okHandle instanceof Function) {
        okHandle(fields);
      }
    });
  };

  onCancel = () => {
    const { onCancel } = this.props;
    if (onCancel instanceof Function) {
      onCancel();
    }
  };

  afterClose = () => {
    const { form, afterClose } = this.props;
    if (afterClose instanceof Function) {
      afterClose();
    }
    form.resetFields();
  };

  render() {
    const {
      visible,
      form,
      okHandle,
      onCancel,
      submitText,
      cancelText,
      colon,
      layout,
      title,
      itemLayout,
      ...others
    } = this.props;
    return (
      <Modal
        okText={submitText}
        cancelText={cancelText}
        onOk={this.okHandle}
        onCancel={this.onCancel}
        afterClose={this.afterClose}
        visible={visible}
        title={title}
        {...others}
      >
        <Form layout={layout} {...itemLayout}>
          {React.Children.map(this.props.children, child => {
            if (child && ['div', 'p', 'h3'].indexOf(child.type) === -1) {
              const { name } = child.props;
              return React.cloneElement(child, {
                key: name,
                form,
                getFieldDecorator: form.getFieldDecorator,
              });
            }
            return child;
          })}
        </Form>
      </Modal>
    );
  }
}
export default Form.create()(ModalForm);
